<?php

namespace app\v1\controller;

use app\common\model\Config;
use app\common\model\NavMenu;
use app\common\model\SlideItem;
use app\common\model\User;
use app\common\model\UserDevice;
use app\common\model\VerificationCode;

class PublicController extends ApiBaseController
{
    /**
     * @OA\Get(path="/config/website",tags={"公共"},summary="网站信息",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function website()
    {
        $system = Config::find(1);
        return $this->result($system['value']);
    }

    /**
     * @OA\Get(path="/slide",tags={"公共"},summary="幻灯片",
     *   @OA\Parameter(name="slide_id", in="query", description="幻灯片ID", @OA\Schema(type="int", default="1")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function slide()
    {
        $slide_id = $this->request->param('slide_id', 1);
        $list = SlideItem::field('id,slide_id,title,image')->where('slide_id', $slide_id)->order('id','desc')->select();
        return $this->result($list->toArray());
    }

    /**
     * @OA\Get(path="/menu",tags={"公共"},summary="菜单",
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Parameter(name="menu_id", in="query", description="菜单ID", @OA\Schema(type="int", default="1")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function menu()
    {
        $menu_id = $this->request->param('menu_id', 1);
        $list = NavMenu::where('menu_id', $menu_id)->order('id','desc')->select();
        return $this->result($list->toArray());
    }

    public function login()
    {
        $param = $this->request->param();
        $this->validate($param, 'app\common\validate\Login');
        if ($param['captcha'] != VerificationCode::getCode($param['mobile'])) {
            $this->error('验证码错误');
        }

        $user = User::where('mobile', $param['mobile'])->find();
        if (!$user) {
            //注册入库
            $data['username'] = $param['mobile'];
            $data['mobile']   = $param['mobile'];
            $user             = User::create($data);
        }

        // 设备
        UserDevice::assign($user->id, $param);

        $this->success('登录成功!', $user);
    }
}